package article

import (
	"BookStack/pkg/errors"
)

// ArticleNotFound 文章不存在错误
func ArticleNotFound(articleID interface{}) errors.AppError {
	return errors.New(errors.ErrCodeArticleNotFound, "").WithDetails(map[string]interface{}{
		"article_id": articleID,
	})
}

// ArticleAlreadyExists 文章已存在错误
func ArticleAlreadyExists(title string) errors.AppError {
	return errors.New(errors.ErrCodeArticleAlreadyExists, "").WithDetails(map[string]interface{}{
		"title": title,
	})
}

// InvalidArticleData 无效的文章数据
func InvalidArticleData(details map[string]interface{}) errors.AppError {
	return errors.New(errors.ErrCodeInvalidArticleData, "").WithDetails(details)
}

// InvalidStatus 文章状态无效
func InvalidStatus(status interface{}) errors.AppError {
	return errors.New(errors.ErrCodeArticleStatusInvalid, "").WithDetails(map[string]interface{}{
		"status": status,
	})
}

// ValidationFailed 验证失败
func ValidationFailed(fields map[string]string) errors.AppError {
	// 将字符串错误消息转换为错误码
	fieldErrors := make(map[string]int)
	for field, msg := range fields {
		switch {
		case field == "Title" && msg == "标题不能为空":
			fieldErrors[field] = errors.ErrCodeArticleTitleRequired
		case field == "Slug" && msg == "文章标识不能为空":
			fieldErrors[field] = errors.ErrCodeArticleSlugRequired
		case field == "ID" && msg == "文章ID不能为空":
			fieldErrors[field] = errors.ErrCodeArticleIDRequired
		case field == "Status" && msg == "文章状态不能为空":
			fieldErrors[field] = errors.ErrCodeArticleStatusRequired
		case field == "Title" && msg == "标题长度超过限制":
			fieldErrors[field] = errors.ErrCodeArticleTitleMaxLength
		case field == "Slug" && msg == "文章标识长度超过限制":
			fieldErrors[field] = errors.ErrCodeArticleSlugMaxLength
		case field == "Summary" && msg == "摘要长度超过限制":
			fieldErrors[field] = errors.ErrCodeArticleSummaryMaxLength
		case field == "CoverImage" && msg == "封面图片长度超过限制":
			fieldErrors[field] = errors.ErrCodeArticleCoverMaxLength
		case field == "body" && msg == "请求JSON格式不正确，请检查语法":
			return errors.JSONFormatError()
		default:
			// 对于未识别的错误，使用通用验证错误
			return errors.New(errors.ErrCodeValidation, "").WithDetails(map[string]interface{}{
				"fields": fields,
			})
		}
	}

	return errors.ValidationErrors(fieldErrors)
}

// DatabaseError 数据库错误
func DatabaseError(err error) errors.AppError {
	return errors.Wrap(err, errors.ErrCodeDatabase, "")
}
